/*
 * Copyright (c) 2020 hebeiyiliuba.com
 * All rights reserved.
 *
 */
package org.jeecg.modules.third.jg.report.freight.information.service;

import com.dy.wlhy.client.Body;
import com.dy.wlhy.client.BuildContent;
import com.dy.wlhy.client.BuildSign;
import com.dy.wlhy.client.Constant;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.third.jg.report.freight.information.util.sm.SM2Util;
import org.jeecg.modules.third.jg.report.freight.information.util.sm.SM4Util;

/**
 * @BelongsPackage: org.jeecg.modules.third.jg.report.freight.information.service
 * @Author: duanlikao
 * @CreateTime: 2023-03-25 10:30
 * @Description:
 * @Version: 1.0
 */
@Slf4j
public abstract class LiaoNingUtils extends Constant {
    public LiaoNingUtils() {
    }

    protected static byte[] digest(String algorithm, byte[] source) {
        try {
            MessageDigest md = MessageDigest.getInstance(algorithm);
            return md.digest(source);
        } catch (NoSuchAlgorithmException var3) {
            throw new IllegalArgumentException(var3);
        }
    }

    protected static String hexEncode(byte[] bytes) {
        byte[] source = bytes;
        StringBuilder hs = new StringBuilder();
        String stmp = "";

        for(int n = 0; n < source.length; ++n) {
            stmp = Integer.toHexString(source[n] & 255);
            if (stmp.length() == 1) {
                hs.append('0').append(stmp);
            } else {
                hs.append(stmp);
            }
        }

        String codeString = hs.toString().toUpperCase();
        return codeString;
    }

    private static String urlEncode(String str) {
        try {
            return URLEncoder.encode(str, "UTF-8");
        } catch (UnsupportedEncodingException var2) {
            var2.printStackTrace();
            return null;
        }
    }

    private static String formatDate(Date date, String format) {
        if (date == null) {
            return "";
        } else {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
            simpleDateFormat.setLenient(false);
            return simpleDateFormat.format(date);
        }
    }

    private static String getResult(String url, String content) {
        HttpURLConnection connection = null;

        try {
            URL requestUrl = new URL(url);
            connection = (HttpURLConnection)requestUrl.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.connect();
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.write(content.getBytes("utf-8"));
            out.flush();
            out.close();
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
            StringBuffer buffer = new StringBuffer();
            String line = "";

            while((line = reader.readLine()) != null) {
                buffer.append(line);
            }

            reader.close();
            String var9 = buffer.toString();
            return var9;
        } catch (Exception var12) {
            var12.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }

        }

        return null;
    }

    private static String getRetEncodeKey() {
        try {
            return SM4Util.generateKey();
        } catch (Exception var1) {
            var1.printStackTrace();
            return "";
        }
    }

    private static Body getEncodeBody(String signSb, String publickey) {
        Body body = null;

        try {
            String key = SM4Util.generateKey();
            body = new Body();
            String encryptBase64 = SM4Util.encrypt_Ecb_Padding(key, signSb);
            body.setEncryptedContent(urlEncode(encryptBase64));
            String encrypt = SM2Util.encrypt(publickey, key);
            body.setEncryptedCode(encrypt);
        } catch (Exception var6) {
            var6.printStackTrace();
        }

        return body;
    }

    private static String getPostBodyContent(String serviceCode, String appkey, String secret, String param, String retkey) {
        String serialnum = UUID.randomUUID().toString().replaceAll("-", "");
        String timestamp = formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
        String sign = BuildSign.buildSign(serviceCode, appkey, secret, "SHA", "1.0", "xml", "xml", serialnum, timestamp, param);
        String postcontent = BuildContent.buildPostContent("SHA", "1.0", "xml", "xml", serialnum, timestamp, param, sign, appkey, retkey);
        Body encbody = getEncodeBody(postcontent, "04CE0FEA1C40665A83380E883CF8A8787823702D05245EB36784B21A6FD3E5C57CE557CEB0555D96097FA5264E2F1E2C18EE0A6454E4E5DF116A57DE711C36111C");
        String postBodyContent = BuildContent.buildBodyContent(encbody);
        return postBodyContent;
    }

    public static String send(int seq, String appkey, String secret, String param) {
        String serviceName = getServiceName(seq);
        if (!"".equals(serviceName) && !"".equals(param) && param != null) {
            String ret = null;
            String retKey = getRetEncodeKey();

            try {
                String serviceCode = "/wccyjc" + serviceName;
                log.info("serviceCode:{}", serviceCode);
                ret = getResult("http://tservice.lnyg.net/services" + serviceCode, getPostBodyContent(serviceCode, appkey, secret, param, retKey));
                if (ret != null) {
                    return SM4Util.decrypt_Ecb_Padding(retKey, ret);
                }
            } catch (Exception var8) {
                var8.printStackTrace();
            }

            return null;
        } else {
            return "";
        }
    }

    private static String getServiceName(int seq) {
        switch(seq) {
            case 1:
                return "/dzydsb/qysb";
            case 2:
                return "/zjls/qyzjlssb";
            case 3:
                return "/clxx/qyclxxsb";
            case 4:
                return "/jsy/qyjsysb";
            case 5:
                return "/qyxx/qyxxsb";
            default:
                return "";
        }
    }
}

